<template>
  <view class="container">

    <!-- 宠物信息 -->
    <view class="pet-info-card centered" v-if="pet" @click="goToPetDetail">
      <view class="pet-info">
        <image :src="pet.photo || '/static/img/default-pet.png'" class="pet-avatar" mode="aspectFill"></image>
        <view class="pet-details">
          <text class="pet-name">{{ pet.name }}</text>
          <text class="pet-breed">{{ pet.breed }}</text>
        </view>
      </view>
    </view>

    <!-- 记录详情卡片 -->
    <view class="detail-card" v-if="record">
      <view class="record-header">
        <view class="record-icon">{{ getReminderIcon(record.reminderType) }}</view>
        <view class="record-title">{{ record.title }}</view>
      </view>

      <view class="record-info">
        <view class="info-item">
          <text class="info-label">提醒类型:</text>
          <text class="info-value">{{ record.reminderType || record.reminder_type || '无数据' }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">提醒日期:</text>
          <text class="info-value reminder-date">{{ formatDate(record.reminderTime) }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">状态:</text>
          <text class="info-value" :class="getStatusClass(record.status)">{{ getStatusText(record.status) }}</text>
        </view>
        

        
        <view class="info-item">
          <text class="info-label">创建时间:</text>
          <text class="info-value">{{ formatDateTime(record.createTime) }}</text>
        </view>
      </view>

      <view class="record-remark">
        <text class="remark-title">备注:</text>
        <text class="remark-content">{{ record.remark}}</text>
      </view>
    </view>

    <!-- 健康记录信息 -->
    <view class="health-record-card" v-if="healthRecord" @click="goToHealthRecordDetail">
      <view class="card-title">健康记录</view>
      <view class="health-record-info">
        <view class="health-record-icon">📋</view>
        <view class="health-record-details">
          <text class="health-record-type">{{ healthRecord.type || '健康记录' }}</text>
          <text class="health-record-date">{{ formatDate(healthRecord.recordDate) }}</text>
          <text class="health-record-content">{{ healthRecord.content || '无详细内容' }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮区域 -->
    <view class="bottom-action-section">
      <!-- 状态操作按钮 -->
      <view class="action-row" v-if="record && isPendingStatus(record.status)">
        <button class="action-btn complete-btn" @click="markAsCompleted">
          <text class="complete-icon">✓</text>
          <text>标记已完成</text>
        </button>
      </view>
      
      <!-- 编辑和删除按钮 -->
      <view class="action-row" v-if="record">
        <button class="action-btn edit-btn" @click="editRecord">
          <text>编辑</text>
        </button>
        <button class="action-btn delete-btn" @click="deleteRecord">
          <text>删除</text>
        </button>
      </view>
    </view>

    <!-- 右上角菜单已移除，编辑和删除按钮移至底部 -->
  </view>
</template>

<script>
import { getPetDetail } from '@/api/pet.js'
import { getreminderdetail, updatereminder } from '@/api/reminder.js'
import { addHealthRecord, getHealthList } from '@/api/health.js'
import { checkAndRedirectToLogin } from '@/utils/auth.js'
import { API_BASE } from '@/config/config.js'

export default {
  data() {
    return {
      record: null,
      pet: null,
      healthRecord: null,
      savedOptions: null,
      needRefresh: false
    }
  },
  onLoad(options) {
    // 保存options数据，以便在onShow中使用
    this.savedOptions = {...options}
    const recordId = options.id || options.reminderId
    const targetDate = options.date ? new Date(options.date) : null
    if (recordId) {
      this.loadRecordDetail(recordId, targetDate)
    } else {
      console.error('No record ID provided in options');
      uni.showToast({
        title: '缺少提醒ID',
        icon: 'none'
      });
    }
  },
  onShow() {
    // 当页面重新显示时，重新加载数据以确保数据是最新的
    if (this.record && this.record.id) {
      // 检查是否需要刷新（从健康详情页面删除记录后设置）
      if (this.needRefresh) {
        this.needRefresh = false; // 重置刷新标志
      }
      // 保存原始的options数据，以便在onShow中使用
      const savedOptions = this.savedOptions || {}
      const targetDate = savedOptions.date || this.record.date || this.record.reminderTime || new Date()
      this.loadRecordDetail(this.record.id, targetDate)
    }
  },
  methods: {
    async loadRecordDetail(recordId, targetDate = null) {
      try {
        // 使用统一的认证检查函数
        if (!checkAndRedirectToLogin('请先登录')) {
          return
        }
        
        const response = await getreminderdetail(recordId)
        if (response && response.code === 200) {
          this.record = response.data || response

          // 加载相关宠物信息
          if (this.record.petId) {
            this.loadPetInfo(this.record.petId)
          } else {
            if (this.record.pet_id) {
              this.loadPetInfo(this.record.pet_id)
            }
          }
          
          // 检查指定日期的健康记录
          await this.checkHealthRecordForDate(targetDate)
        } else {
          console.error('Business error:', response?.msg)
          uni.showToast({
            title: response?.msg || '加载失败',
            icon: 'none'
          })
        }

      } catch (error) {
        console.error('加载提醒详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    
    async loadPetInfo(petId) {
      try {
        const response = await getPetDetail(petId)
        
        if (response && response.code === 200) {
          this.pet = response.data
        } else {
          console.error('Failed to load pet info:', response?.msg)
        }
      } catch (error) {
        console.error('加载宠物信息失败:', error)
      }
    },
    
    async checkHealthRecordForDate(targetDate = null) {
      try {
        if (!this.record || !this.record.id) {
          return
        }
        
        // 首先尝试从本地存储中获取健康记录数据
        const storageKeys = uni.getStorageInfoSync().keys
        const healthKeys = storageKeys.filter(key => key.startsWith('health_'))
        const tempHealthKeys = storageKeys.filter(key => key.startsWith('temp_health_'))
        
        // 检查是否有与当前提醒ID相关的健康记录
        let foundInStorage = false
        
        // 先检查真实的健康记录
        for (const key of healthKeys) {
          const healthData = uni.getStorageSync(key)
          if (healthData && healthData.reminderId === this.record.id) {
            this.healthRecord = healthData
            foundInStorage = true
            break
          }
        }
        
        // 如果没有找到真实的，检查临时的健康记录
        if (!foundInStorage) {
          for (const key of tempHealthKeys) {
            const healthData = uni.getStorageSync(key)
            if (healthData && healthData.reminderId === this.record.id) {
              this.healthRecord = healthData
              foundInStorage = true
              break
            }
          }
        }
        
        // 获取目标日期，与创建健康记录时使用的逻辑保持一致
        const targetDateForCheck = targetDate || this.savedOptions?.date || this.record.date || this.record.reminderTime || new Date()
        const checkDateStr = new Date(targetDateForCheck).toISOString().slice(0, 10) // YYYY-MM-DD格式
        
        // 查询健康记录列表，过滤条件：reminderId等于当前提醒ID
        // 不传递recordDate参数，让后端返回所有相关记录，前端进行日期过滤
        const params = {
          reminderId: this.record.id
        }
        
          const response = await getHealthList(params)
        
        if (response && response.code === 200 && response.rows) {
          // 查找指定日期的健康记录
          const targetDateRecords = []
          
          for (let i = 0; i < response.rows.length; i++) {
            const record = response.rows[i]
            
            // 检查reminderId匹配 - 使用更宽松的比较
            const recordReminderId = record.reminderId || record.reminder_id
            const targetReminderId = this.record.id
            const reminderMatch = String(recordReminderId) === String(targetReminderId)
            
            // 检查日期匹配 - 使用更宽松的比较
            let dateMatch = false
            const recordDateStr = record.recordDate || record.record_date || ''
            
            if (recordDateStr) {
              // 尝试提取日期部分
              const datePart = recordDateStr.split(' ')[0] || recordDateStr.split('T')[0]
              dateMatch = datePart === checkDateStr
            }
            
            if (reminderMatch && dateMatch) {
              targetDateRecords.push(record)
            }
          }
          
          if (targetDateRecords.length > 0) {
            this.healthRecord = targetDateRecords[0]
          } else {
            this.healthRecord = null
          }
        } else {
            this.healthRecord = null
          }
       } catch (error) {
        console.error('检查健康记录失败:', error)
        this.healthRecord = null
      }
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    goToPetDetail() {
      if (this.pet && this.pet.id) {
        uni.navigateTo({
          url: `/pages/pet/detail?id=${this.pet.id}`
        })
      }
    },
    
    goToHealthRecordDetail() {
      if (this.healthRecord && this.healthRecord.id) {
        // 检查是否为临时ID，如果是则阻止导航
        if (typeof this.healthRecord.id === 'string' && this.healthRecord.id.startsWith('temp_')) {
          uni.showToast({
            title: '健康记录正在同步中，请稍后再试',
            icon: 'none'
          })
          return
        }
        
        uni.navigateTo({
          url: `/pages/health/detail?id=${this.healthRecord.id}`
        })
      } else {
        // 如果healthRecord为null或没有id，说明数据还在同步中
        uni.showToast({
          title: '健康记录正在同步中，请稍后再试',
          icon: 'none'
        })
      }
    },
    

    
    editRecord() {
      uni.navigateTo({
        url: `/pages/calendar/edit?id=${this.record.id}`
      })
    },
    
    deleteRecord() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个提醒吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await uni.request({
                url: `${API_BASE}/system/reminder/${this.record.id}`,
                method: 'DELETE',
                header: {
                  'Authorization': 'Bearer ' + uni.getStorageSync('token'),
                  'Content-Type': 'application/json'
                }
              })
              
              if (response.statusCode === 200) {
                const responseData = response.data
                if (responseData && responseData.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                setTimeout(() => {
                  uni.navigateBack()
                }, 1500)
                } else {
                  uni.showToast({
                    title: responseData?.msg || '删除失败',
                    icon: 'none'
                  })
                }
              } else {
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              console.error('删除提醒失败:', error)
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    async markAsCompleted() {
      uni.showModal({
        title: '确认完成',
        content: '确定要将此提醒标记为已完成吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              // 检查是否为重复提醒
              const isRepeatReminder = this.record.repeatType && this.record.repeatType !== '0' && this.record.repeatType !== '不重复'
              
              let response = null
              
              if (isRepeatReminder) {
                // 重复提醒不改变状态，只创建健康记录
              } else {
                // 非重复提醒，改变状态为已完成
                const updateData = {
                  ...this.record,
                  status: '1' // 使用数字状态码
                }
                
                // 使用封装的updatereminder方法
                response = await updatereminder(this.record.id, updateData)
                
                if (response && response.code === 200) {
                  this.record.status = '1'
                }
              }
              
              // 创建健康记录
              await this.createHealthRecord()
              
              uni.showToast({
                title: isRepeatReminder ? '已创建健康记录' : '标记成功并已创建健康记录',
                icon: 'success'
              })
              
              // 等待健康记录创建完成后再刷新页面
              const checkHealthRecord = setInterval(() => {
                if (this.healthRecord && this.healthRecord.id && !this.healthRecord.id.toString().startsWith('temp_')) {
                  clearInterval(checkHealthRecord)
                  // 刷新当前页面，重新加载数据
                  const pages = getCurrentPages()
                  const currentPage = pages[pages.length - 1]
                  // 先强制更新数据
                  this.$forceUpdate()
                  // 重新加载页面数据
                  currentPage.onLoad(currentPage.options)
                  currentPage.onShow()
                  // 再次强制更新确保UI刷新
                  this.$forceUpdate()
                }
              }, 100)
              
              // 设置超时，避免无限等待
              setTimeout(() => {
                clearInterval(checkHealthRecord)
                // 即使没有健康记录也刷新页面
                const pages = getCurrentPages()
                const currentPage = pages[pages.length - 1]
                this.$forceUpdate()
                currentPage.onLoad(currentPage.options)
                currentPage.onShow()
                this.$forceUpdate()
              }, 3000)
            } catch (error) {
              console.error('标记完成失败:', error)
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    async createHealthRecord() {
      try {
        // 确保有宠物ID
        const petId = this.record.petId || this.record.pet_id
        if (!petId) {
          console.error('创建健康记录失败：缺少宠物ID')
          uni.showToast({
            title: '创建健康记录失败：缺少宠物ID',
            icon: 'none'
          })
          return
        }
        
        // 构建健康记录数据，确保包含所有必需字段
        const now = new Date()
        // 获取提醒日期，应该使用提醒的日期而不是当前日期
        // 优先使用options.date（传入的日期），然后是record.reminderTime，最后是当前日期
        const targetDate = this.options?.date || this.record.reminderTime || new Date()
        
        const healthRecord = {
          petId: Number(petId), // 宠物ID（必需）- 转换为数字类型
          type: this.record.reminderType || this.record.reminder_type || '其他', // 提醒类型（必需）
          content: this.record.title, // 标题作为内容（必需）
          status: '1', // 状态：0-正常（根据后端定义）
          createTime: this.formatDateTime(now), // 创建时间- 格式化为后端期望格式
          createBy: 'system', // 创建者
          reminderId: this.record.id, // 提醒ID（新增字段）
          recordDate: this.formatDateTime(new Date(targetDate)) // 记录日期字段（新增字段）- 使用目标日期，包含完整日期时间格式
        }
        

        
        // 如果有备注信息，添加到content中
        if (this.record.remark) {
          healthRecord.content += ` - ${this.record.remark}`
        }
        

        
        // 使用封装的addHealthRecord方法
        const response = await addHealthRecord(healthRecord)
        
        if (response && response.code === 200) {
          // 获取创建的健康记录ID
          const healthRecordId = response.data?.id || response.data
          
          if (healthRecordId) {
            // 更新提醒记录，设置healthRecordId
            await this.updateReminderWithHealthRecord(this.record.id, healthRecordId)
            
            this.healthRecord = {
              id: healthRecordId,
              reminderId: this.record.id,
              recordDate: this.formatDateTime(new Date()),
              type: this.record.reminderType || this.record.reminder_type || '其他',
              content: this.record.title
            }
            
            // 删除之前可能存在的临时数据
            const tempKeys = uni.getStorageInfoSync().keys.filter(key => key.startsWith('temp_health_'))
            tempKeys.forEach(key => {
              const tempData = uni.getStorageSync(key)
              if (tempData && tempData.reminderId === this.record.id) {
                uni.removeStorageSync(key)
              }
            })
            
            // 确保页面数据更新
            this.$forceUpdate()
          } else {
            // 如果响应中没有返回ID，尝试通过查询获取刚创建的健康记录
            try {
              const now = new Date()
              const todayStr = now.toISOString().slice(0, 10) // YYYY-MM-DD格式
              const queryParams = {
                reminderId: this.record.id,
                // 可以添加其他查询条件如日期范围等
              }
              
              const healthListResponse = await getHealthList(queryParams)
              
              if (healthListResponse && healthListResponse.code === 200 && healthListResponse.rows) {
                // 查找今天创建的记录
                const todayRecords = healthListResponse.rows.filter(record => {
                  const recordDate = new Date(record.recordDate).toISOString().slice(0, 10)
                  return recordDate === todayStr && record.reminderId == this.record.id
                })
                
                if (todayRecords.length > 0) {
                  // 使用最新创建的记录
                  const latestRecord = todayRecords[todayRecords.length - 1]
                  this.healthRecord = {
                    id: latestRecord.id,
                    reminderId: latestRecord.reminderId,
                    recordDate: latestRecord.recordDate,
                    type: latestRecord.type || this.record.reminderType || this.record.reminder_type || '其他',
                    content: latestRecord.content || this.record.title
                  }
                  
                  // 更新提醒记录，设置healthRecordId
                  await this.updateReminderWithHealthRecord(this.record.id, latestRecord.id)
                  
                  // 删除之前可能存在的临时数据
                  const tempKeys = uni.getStorageInfoSync().keys.filter(key => key.startsWith('temp_health_'))
                  tempKeys.forEach(key => {
                    const tempData = uni.getStorageSync(key)
                    if (tempData && tempData.reminderId === this.record.id) {
                      uni.removeStorageSync(key)
                    }
                  })
                } else {
                  // 如果查询不到记录，等待1秒后重试
                  setTimeout(async () => {
                    try {
                      const retryResponse = await getHealthList(queryParams)
                      if (retryResponse && retryResponse.code === 200 && retryResponse.rows) {
                        const retryRecords = retryResponse.rows.filter(record => {
                          const recordDate = new Date(record.recordDate).toISOString().slice(0, 10)
                          return recordDate === todayStr && record.reminderId == this.record.id
                        })
                        
                        if (retryRecords.length > 0) {
                          const latestRecord = retryRecords[retryRecords.length - 1]
                          this.healthRecord = {
                            id: latestRecord.id,
                            reminderId: latestRecord.reminderId,
                            recordDate: latestRecord.recordDate,
                            type: latestRecord.type || this.record.reminderType || this.record.reminder_type || '其他',
                            content: latestRecord.content || this.record.title
                          }
                          await this.updateReminderWithHealthRecord(this.record.id, latestRecord.id)
                          
                          // 删除临时数据
                          const tempKeys = uni.getStorageInfoSync().keys.filter(key => key.startsWith('temp_health_'))
                          tempKeys.forEach(key => {
                            const tempData = uni.getStorageSync(key)
                            if (tempData && tempData.reminderId === this.record.id) {
                              uni.removeStorageSync(key)
                            }
                          })
                          
                          this.$forceUpdate()
                        }
                      }
                    } catch (retryError) {
                      console.error('重试查询健康记录失败:', retryError)
                    }
                  }, 1000)
                }
              } else {
                // 查询失败，等待1秒后重试
                setTimeout(async () => {
                  try {
                    const retryResponse = await getHealthList(queryParams)
                    if (retryResponse && retryResponse.code === 200 && retryResponse.rows) {
                      const retryRecords = retryResponse.rows.filter(record => {
                        const recordDate = new Date(record.recordDate).toISOString().slice(0, 10)
                        return recordDate === todayStr && record.reminderId == this.record.id
                      })
                      
                      if (retryRecords.length > 0) {
                        const latestRecord = retryRecords[retryRecords.length - 1]
                        this.healthRecord = {
                          id: latestRecord.id,
                          reminderId: latestRecord.reminderId,
                          recordDate: latestRecord.recordDate,
                          type: latestRecord.type || this.record.reminderType || this.record.reminder_type || '其他',
                          content: latestRecord.content || this.record.title
                        }
                        await this.updateReminderWithHealthRecord(this.record.id, latestRecord.id)
                        
                        // 删除临时数据
                        const tempKeys = uni.getStorageInfoSync().keys.filter(key => key.startsWith('temp_health_'))
                        tempKeys.forEach(key => {
                          const tempData = uni.getStorageSync(key)
                          if (tempData && tempData.reminderId === this.record.id) {
                            uni.removeStorageSync(key)
                          }
                        })
                        
                        this.$forceUpdate()
                      }
                    }
                  } catch (retryError) {
                    console.error('重试查询健康记录失败:', retryError)
                  }
                }, 1000)
              }
            } catch (error) {
              console.error('查询健康记录失败:', error)
              // 查询异常，等待1秒后重试
              setTimeout(async () => {
                try {
                  const retryResponse = await getHealthList(queryParams)
                  if (retryResponse && retryResponse.code === 200 && retryResponse.rows) {
                    const retryRecords = retryResponse.rows.filter(record => {
                      const recordDate = new Date(record.recordDate).toISOString().slice(0, 10)
                      return recordDate === todayStr && record.reminderId == this.record.id
                    })
                    
                    if (retryRecords.length > 0) {
                      const latestRecord = retryRecords[retryRecords.length - 1]
                      this.healthRecord = {
                        id: latestRecord.id,
                        reminderId: latestRecord.reminderId,
                        recordDate: latestRecord.recordDate,
                        type: latestRecord.type || this.record.reminderType || this.record.reminder_type || '其他',
                        content: latestRecord.content || this.record.title
                      }
                      await this.updateReminderWithHealthRecord(this.record.id, latestRecord.id)
                      
                      // 删除临时数据
                      const tempKeys = uni.getStorageInfoSync().keys.filter(key => key.startsWith('temp_health_'))
                      tempKeys.forEach(key => {
                        const tempData = uni.getStorageSync(key)
                        if (tempData && tempData.reminderId === this.record.id) {
                          uni.removeStorageSync(key)
                        }
                      })
                      
                      uni.setStorageSync(`health_${latestRecord.id}`, this.healthRecord)
                      this.$forceUpdate()
                    }
                  }
                } catch (retryError) {
                  console.error('重试查询健康记录失败:', retryError)
                }
              }, 1000)
            }
          }
          
          // 强制更新页面状态
          this.$forceUpdate()
          
          uni.showToast({
            title: '健康记录创建成功',
            icon: 'success'
          })
        } else {
          console.error('健康记录创建失败:', response?.msg)
          uni.showToast({
            title: `健康记录创建失败: ${response?.msg || '未知错误'}`,
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('创建健康记录失败:', error)
        uni.showToast({
          title: '创建健康记录失败',
          icon: 'none'
        })
      }
    },
    
    // 更新提醒记录，设置健康记录ID
    async updateReminderWithHealthRecord(reminderId, healthRecordId) {
      try {
        const updateData = {
          healthRecordId: healthRecordId
        }
        
        const response = await updatereminder(reminderId, updateData)
        
        if (response && response.code === 200) {
          // 更新成功
        } else {
          console.error('提醒记录更新失败:', response?.msg)
        }
      } catch (error) {
        console.error('更新提醒记录失败:', error)
      }
    },
    
    getReminderIcon(type) {
      const icons = {
        '疫苗': '💉',
        '驱虫': '🦠',
        '体检': '🏥',
        '体重': '⚖️',
        '喂药': '💊',
        '洗澡': '🛁',
        '美容': '✂️',
        '运动': '🏃',
        '其他': '📋'
      }
      return icons[type] || '📋'
    },
    
    isPendingStatus(status) {
      // 如果有健康记录，说明当天已完成，不显示待处理状态
      if (this.healthRecord) {
        return false
      }
      // 统一判断待处理状态：支持数字0、字符串'0'、英文'pending'
      return status === '0' || status === 0 || status === 'pending'
    },
    
    isCompletedStatus(status) {
      // 如果有健康记录，说明当天已完成，显示已完成状态
      if (this.healthRecord) {
        return true
      }
      // 统一判断已完成状态：支持数字1、字符串'1'、英文'completed'
      return status === '1' || status === 1 || status === 'completed'
    },
    
    getStatusClass(status) {
      // 如果有健康记录，说明当天已完成，显示已完成样式
      if (this.healthRecord) {
        return 'status-completed'
      }
      // 统一处理状态样式类：支持数字0/1、字符串'0'/'1'、英文'pending'/'completed'/'overdue'
      if (status === '0' || status === 0 || status === 'pending') {
        return 'status-pending'
      } else if (status === '1' || status === 1 || status === 'completed') {
        return 'status-completed'
      } else if (status === 'overdue') {
        return 'status-overdue'
      }
      return 'status-pending'
    },
    
    getStatusText(status) {
      // 如果有健康记录，说明当天已完成，显示已完成文本
      if (this.healthRecord) {
        return '已完成'
      }
      // 统一处理状态值：支持数字0/1、字符串'0'/'1'、英文'pending'/'completed'/'overdue'
      if (status === '0' || status === 0 || status === 'pending') {
        return '待处理'
      } else if (status === '1' || status === 1 || status === 'completed') {
        return '已完成'
      } else if (status === 'overdue') {
        return '已逾期'
      }
      return '待处理'
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.container {
  background: white;
  min-height: 100vh;
  padding: 20rpx;
  padding-bottom: 300rpx; /* 为底部按钮留出更多空间 */
  border-radius: 15rpx;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
}

.back-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.menu-btn {
  background: none;
  border: none;
  padding: 10rpx;
  position: relative;
}

.menu-icon {
  font-size: 40rpx;
  color: #333;
  font-weight: bold;
}

/* 菜单遮罩层 */
.menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  z-index: 99;
}

/* 下拉菜单 */
.menu-dropdown {
  position: fixed;
  top: 100rpx;
  right: 20rpx;
  background: #fff;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  z-index: 100;
  min-width: 200rpx;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item-icon {
  font-size: 28rpx;
  margin-right: 15rpx;
}

.menu-item text {
  font-size: 28rpx;
  color: #333;
}

.detail-card {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.08);
}

.record-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.record-icon {
  font-size: 60rpx;
  margin-right: 20rpx;
}

.record-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.record-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: bold;
}

.status-pending {
  background: #FFF3CD;
  color: #856404;
}

.status-completed {
  background: #D4EDDA;
  color: #155724;
}

.status-overdue {
  background: #F8D7DA;
  color: #721C24;
}

.record-info {
  margin-bottom: 30rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #666;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.reminder-date {
  color: #FF9500;
}

.record-description, .record-remark {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.description-title, .remark-title {
  font-size: 28rpx;
  color: #666;
}

.description-content, .remark-content {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.pet-info-card {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  margin-top: 20rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}

.pet-info-card.centered {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 40rpx 30rpx;
}

.pet-info-card:hover {
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
  transform: translateY(-2rpx);
}

.card-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.pet-info {
  display: flex;
  align-items: center;
}

.centered .pet-info {
  flex-direction: column;
  text-align: center;
}

.pet-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.centered .pet-avatar {
  width: 120rpx;
  height: 120rpx;
  margin-right: 0;
  margin-bottom: 20rpx;
}

.pet-details {
  flex: 1;
}

.centered .pet-details {
  flex: none;
  width: 100%;
}

.pet-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
}

.centered .pet-name {
  font-size: 32rpx;
  text-align: center;
}

.pet-breed {
  font-size: 24rpx;
  color: #666;
}

.centered .pet-breed {
  font-size: 26rpx;
  text-align: center;
}

/* 底部操作按钮区域 */
.bottom-action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  width: calc(100% - 20rpx);
  background: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.08);
  z-index: 10;
}

.action-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.action-row:last-child {
  margin-bottom: 0;
}

.action-btn {
  flex: 1;
  padding: 20rpx;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.edit-btn {
  background: #007AFF;
  color: #fff;
}

.delete-btn {
  background: #fff;
  color: #999;
  border: 1px solid #999;
  margin-right: 1px;
}

.complete-btn {
  background: #4CAF50;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.complete-icon {
  font-size: 32rpx;
  font-weight: bold;
}

.primary {
  background: #007AFF;
  color: #fff;
}

.secondary {
  background: #f0f0f0;
  color: #333;
}

/* 健康记录卡片样式 */
.health-record-card {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 6rpx solid #4CAF50;
}

.health-record-card:hover {
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
  transform: translateY(-2rpx);
}

.health-record-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.health-record-icon {
  font-size: 50rpx;
  margin-right: 20rpx;
  margin-top: 5rpx;
}

.health-record-details {
  flex: 1;
}

.health-record-type {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.health-record-date {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.health-record-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  display: block;
}

.health-record-status {
  display: flex;
  justify-content: flex-end;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: bold;
}

.status-badge.completed {
  background: #D4EDDA;
  color: #155724;
}
</style>